<template>
  <div class="leader-apply page-container">
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">团长申请</h1>
        <p class="page-subtitle">管理团长申请审核，处理申请相关事务</p>
      </div>
    </div>

    <div class="content-card">
      <div class="search-section">
        <el-input
          v-model="searchForm.phone"
          placeholder="手机号"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.realName"
          placeholder="真实姓名"
          class="search-input"
          clearable
        />
        <el-input
          v-model="searchForm.customerId"
          placeholder="用户ID"
          class="search-input"
          clearable
        />
        <el-select
          v-model="searchForm.applyStatus"
          placeholder="申请状态"
          clearable
          class="status-select"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="审核驳回" :value="2" />
          <el-option label="已取消" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <el-table
        :data="applyList"
        style="width: 100%"
        class="apply-table"
        v-loading="loading"
        row-key="id"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column
          prop="customerId"
          label="用户ID"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="realName"
          label="真实姓名"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="phone"
          label="手机号"
          width="130"
          show-overflow-tooltip
        />
        <el-table-column
          prop="address"
          label="地址"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="applyReason"
          label="申请原因"
          width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="applyStatus"
          label="申请状态"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.applyStatus)" size="small">
              {{ getStatusText(row.applyStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditorName"
          label="审核人"
          width="100"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditorName">{{ row.auditorName }}</span>
            <span v-else class="no-auditor">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditTime"
          label="审核时间"
          width="160"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditTime">{{ row.auditTime }}</span>
            <span v-else class="no-audit">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditOpinion"
          label="审核意见"
          width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span v-if="row.auditOpinion">{{ row.auditOpinion }}</span>
            <span v-else class="no-opinion">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdTime"
          label="申请时间"
          width="160"
          show-overflow-tooltip
        />

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <!-- 待审核状态：显示同意和拒绝按钮 -->
              <template v-if="row.applyStatus === 0">
                <el-button
                  size="small"
                  type="success"
                  @click="approveApply(row)"
                  class="action-btn"
                >
                  同意
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="rejectApply(row)"
                  class="action-btn"
                >
                  拒绝
                </el-button>
              </template>

              <!-- 其他状态：显示详情按钮 -->
              <template v-else>
                <el-button
                  size="small"
                  type="info"
                  @click="viewDetail(row)"
                  class="action-btn"
                >
                  详情
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'agree' ? '同意申请' : '拒绝申请'"
      width="500px"
      @close="resetAuditForm"
    >
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="申请人">
          <el-input :value="auditForm.realName" disabled />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input :value="auditForm.phone" disabled />
        </el-form-item>
        <el-form-item label="审核意见" required>
          <el-input
            v-model="auditForm.auditOpinion"
            type="textarea"
            :rows="4"
            :placeholder="`请输入${
              auditType === 'agree' ? '同意' : '拒绝'
            }的审核意见`"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button
            :type="auditType === 'agree' ? 'success' : 'danger'"
            @click="confirmAudit"
          >
            确定{{ auditType === "agree" ? "同意" : "拒绝" }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="600px">
      <div v-if="selectedApply" class="apply-detail">
        <div class="detail-section">
          <h4>申请信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>申请ID:</label>
              <span>{{ selectedApply.id }}</span>
            </div>
            <div class="detail-item">
              <label>用户ID:</label>
              <span>{{ selectedApply.customerId }}</span>
            </div>
            <div class="detail-item">
              <label>真实姓名:</label>
              <span>{{ selectedApply.realName }}</span>
            </div>
            <div class="detail-item">
              <label>手机号:</label>
              <span>{{ selectedApply.phone }}</span>
            </div>
            <div class="detail-item">
              <label>地址:</label>
              <span>{{ selectedApply.address }}</span>
            </div>
            <div class="detail-item">
              <label>申请原因:</label>
              <span>{{ selectedApply.applyReason }}</span>
            </div>
            <div class="detail-item">
              <label>申请状态:</label>
              <el-tag
                :type="getStatusTagType(selectedApply.applyStatus)"
                size="small"
              >
                {{ getStatusText(selectedApply.applyStatus) }}
              </el-tag>
            </div>
            <div class="detail-item">
              <label>申请时间:</label>
              <span>{{ selectedApply.createdTime }}</span>
            </div>
          </div>
        </div>

        <div
          v-if="selectedApply.auditorName || selectedApply.auditOpinion"
          class="detail-section"
        >
          <h4>审核信息</h4>
          <div class="detail-grid">
            <div class="detail-item">
              <label>审核人:</label>
              <span>{{ selectedApply.auditorName || "-" }}</span>
            </div>
            <div class="detail-item">
              <label>审核时间:</label>
              <span>{{ selectedApply.auditTime || "-" }}</span>
            </div>
            <div class="detail-item full-width">
              <label>审核意见:</label>
              <span>{{ selectedApply.auditOpinion || "-" }}</span>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";

// 类型定义
interface LeaderApplyInfo {
  id: string;
  customerId: string;
  realName: string;
  phone: string;
  address: string;
  applyReason: string;
  applyStatus: number;
  auditorName: string | null;
  auditTime: string | null;
  auditOpinion: string;
  createdTime: string;
}

const loading = ref(false);
const applyList = ref<LeaderApplyInfo[]>([]);
const auditDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const selectedApply = ref<LeaderApplyInfo | null>(null);
const auditType = ref<"agree" | "refuse">("agree");

// 搜索表单
const searchForm = ref({
  phone: "",
  realName: "",
  customerId: "",
  applyStatus: "", // 这里保持空字符串作为默认值（表示不筛选状态）
});

// 分页
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 审核表单
const auditForm = ref({
  id: "",
  realName: "",
  phone: "",
  auditOpinion: "",
});

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: "待审核",
    1: "审核通过",
    2: "审核驳回",
    3: "已取消",
  };
  return statusMap[status] || "未知状态";
};

// 获取状态标签类型
const getStatusTagType = (status: number): string => {
  const typeMap: Record<number, string> = {
    0: "warning", // 待审核
    1: "success", // 审核通过
    2: "danger", // 审核驳回
    3: "info", // 已取消
  };
  return typeMap[status] || "info";
};

// 获取申请列表
const fetchApplyList = async () => {
  loading.value = true;
  try {
    const params = {
      phone: searchForm.value.phone || "",
      realName: searchForm.value.realName || "",
      customerId: searchForm.value.customerId || "",
      applyStatus:
        searchForm.value.applyStatus === ""
          ? ""
          : searchForm.value.applyStatus.toString(),
      pageIndex: currentPage.value.toString(),
      pageSize: pageSize.value.toString(),
    };

    const res = await postWithAuth(
      "/internal/customer/leaderApplyList",
      params
    );
    if (res.code === 0 && res.data) {
      applyList.value = Array.isArray(res.data.list) ? res.data.list : [];
      total.value = Number(res.data.total || 0);
    } else {
      applyList.value = [];
      total.value = 0;
      ElMessage.error(res.message || "获取申请列表失败");
    }
  } catch (error) {
    console.error("获取申请列表失败:", error);
    ElMessage.error("获取申请列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchApplyList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    phone: "",
    realName: "",
    customerId: "",
    applyStatus: "",
  };
  currentPage.value = 1;
  fetchApplyList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchApplyList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchApplyList();
};

// 同意申请
const approveApply = (row: LeaderApplyInfo) => {
  auditType.value = "agree";
  auditForm.value.id = row.id;
  auditForm.value.realName = row.realName;
  auditForm.value.phone = row.phone;
  auditForm.value.auditOpinion = "";
  auditDialogVisible.value = true;
};

// 拒绝申请
const rejectApply = (row: LeaderApplyInfo) => {
  auditType.value = "refuse";
  auditForm.value.id = row.id;
  auditForm.value.realName = row.realName;
  auditForm.value.phone = row.phone;
  auditForm.value.auditOpinion = "";
  auditDialogVisible.value = true;
};

// 确认审核
const confirmAudit = async () => {
  if (!auditForm.value.auditOpinion.trim()) {
    ElMessage.warning("请输入审核意见");
    return;
  }

  try {
    const response = await postWithAuth("/internal/customer/auditLeaderApply", {
      id: Number(auditForm.value.id),
      review: auditType.value,
      auditOpinion: auditForm.value.auditOpinion,
    });

    if (response.code === 0) {
      ElMessage.success(
        `申请${auditType.value === "agree" ? "同意" : "拒绝"}成功`
      );
      auditDialogVisible.value = false;
      fetchApplyList();
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("审核失败:", error);
    ElMessage.error("操作失败");
  }
};

// 重置审核表单
const resetAuditForm = () => {
  auditForm.value = {
    id: "",
    realName: "",
    phone: "",
    auditOpinion: "",
  };
};

// 查看详情
const viewDetail = (row: LeaderApplyInfo) => {
  selectedApply.value = row;
  detailDialogVisible.value = true;
};

onMounted(() => {
  fetchApplyList();
});
</script>

<style scoped>
.leader-apply {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.search-section {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  width: 200px;
}

.status-select {
  width: 150px;
}

.apply-table {
  margin: 0;
}

.no-auditor,
.no-audit,
.no-opinion {
  color: #9ca3af;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.action-btn {
  margin: 0;
}

.pagination-wrapper {
  padding: 20px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f3f4f6;
}

.apply-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: flex-start;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item label {
  font-weight: 500;
  color: #6b7280;
  width: 100px;
  flex-shrink: 0;
}

.detail-item span {
  color: #1f2937;
  word-break: break-all;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }

  .action-btn {
    width: 100%;
  }
}
</style>
